<?php
declare (strict_types=1);

namespace app\admin\controller;

use think\App;
use think\facade\View;
use think\response\Json;
use app\common\model\Level;
use app\common\model\Assets;
use app\common\model\Pro;
use app\common\model\Logs;

use app\common\builder\TableFront;
use app\common\builder\TableBuilder;
use think\exception\ValidateException;

class User extends Base
{
    //主键，默认为id
    protected $pk = 'id';

    //验证器
    protected $validate = 'User';

    //主模型
    protected $model = '\app\common\model\User';

    protected $ruleModel = '\app\common\model\ProRule';

    //额外查询条件
    protected $extraSearch = ['is_active', 'is_service'];
    //普通会员
    public function ordinary()
    {
        return $this->setTable('ordinary', ['delete'], ['add'], ['is_active' => 1]);
    }

    //正式会员
    public function formal()
    {
        return $this->setTable('ordinary', '', ['add'], ['is_active' => 2], 2);
    }

    public function setTable($action, $rb = [], $tb = [], $extra_map = [], $active = 1)
    {
        //构建table
        $tableFront = TableFront::getInstance()
            ->addRow(['type' => 'checkbox', 'fixed' => 'left', 'title' => '全选'])
            ->addRow(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80])
            ->addRow(['field' => 'nickname', 'title' => '姓名', 'modify' => 'add|edit', 'format' => 'input'])
            ->addRow(['field' => 'mobile', 'title' => '手机号', 'modify' => 'add|edit', 'format' => 'input']);
        $tableFront->addRow(['field' => 'create_time', 'title' => '注册时间', 'width' => 150])
            ->addRow(['field' => 'is_lock', 'title' => '锁定登录', 'templet' => '#is_lock', 'width' => 120, 'unresize' => true])
            ->addRow(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 200]);

        $RightButtons = [
            'edit',
            
            'add_place' => [
                'type' => 'edit',
                'title' => '授权检查',
                'width' => 1400,
                'height' => 1200,
                'url' => url('user/prorule', ['name' => request()->controller() . '_' . request()->action()])->build(),
            ],
            // 'login' => ['title' => '登录', 'type' => 'login', 'url' => url('user/login')->build()],
        ];
        $RightButtons = $rb ? array_merge($RightButtons, $rb) : $RightButtons;
        $TopButtons = [
            'reset_1' => [
                'title' => '重置登录密码', 'icon' => 'layui-icon-password',
                'url'   => url('user/reset')->build(), 'onclick' => 'buttons.reset($(this),1);'],
            // 'reset_2' => [
            //     'title' => '重置支付密码', 'icon' => 'layui-icon-password',
            //     'url'   => url('user/reset')->build(), 'onclick' => 'buttons.reset($(this),2);'],
            //'export'
        ];
        $TopButtons = $tb ? array_merge($tb, $TopButtons) : $TopButtons;

        return TableBuilder::getInstance()
            ->addColumns($tableFront)
            ->addRightButtons($RightButtons)
            ->addTopButtons($TopButtons)
            ->setSearch($this->setSearch($action))
            ->addSwitchTool([['name' => 'is_lock', 'pk' => 'id', 'text' => '锁定|正常']])
            ->addExtraMap($extra_map)
            ->addJsUrl(['user'])
            //->addCensus('\app\common\model\Statistics', 'getUserCensus')
            ->fetch();
    }


    public function setSearch($action = '')
    {
        return TableFront::getInstance()
            ->setSearch(['code__nickname__mobile', '会员编号/昵称/手机号', 'input', '', '', '', 'like']);
    }

    public function add($name = '', $tpl = 'user/add')
    {
        return parent::add($name, $tpl); // TODO: Change the autogenerated stub
    }

    public function edit($name = '', $id = '', $tpl = 'user/edit', $info = '')
    {
        return parent::edit($name, $id, $info); // TODO: Change the autogenerated stub
    }

    public function save($param = [], $model = true): Json
    {
        return parent::save($param, $model); // TODO: Change the autogenerated stub
    }

    public function reset($type)
    {
        try {
            $ids = $this->request->post('ids');
            if ($type == 1) {
                $key = 'password';
                $value = md5('111111');
                $name = '登录密码';
            } else {
                $key = 'pay_password';
                $value = md5('222222');
                $name = '支付密码';
            }
            $this->model::update([$key => $value], ['id' => $ids]);
            $msg = '重置了【' . $name . '】会员标识ID【' . implode(',', $ids) . '】';
            Logs::adds($msg, $this->admin->id, $this->admin->admin_name);
            return json(['code' => 1, 'msg' => '已重置']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

    public function relation()
    {
        try {
            if ($this->request->isAjax()) {
                $id = $this->request->param('id');
                $list = $this->model::where('parent_id', $id)->field('id,code,nickname,mobile')->select();
                foreach ($list as &$v) {
                    $level = $v->level ? $v->level->title : '暂无';
                    $v['title'] = '编号【' . $v['code'] . '】
                    姓名【' . $v->nickname . '】
                    手机号【' . $v->mobile . '】
                    等级【' . $level . '】
                  ';
                }
                return json(['code' => 1, 'msg' => 'success', 'result' => $list]);
            }
            $keyword = $this->request->param('keyword');
            if ($keyword) {
                $map['code|nickname|mobile'] = $keyword;
            } else {
                $map['code'] = 'admin';
            }
            $first = $this->model::where($map)->field('id,code,nickname,mobile')->find();
            if ($first) {
                $level = $first->level ? $first->level->title : '暂无';
                $first['title'] = '编号【' . $first->code . '】
                姓名【' . $first->nickname . '】
                手机号【' . $first->mobile . '】
                等级【' . $level . '】
               ';
            }

            View::assign('first', $first);
            return View::fetch();

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

    public function login($id)
    {
        try {
            $user = $this->model::find($id);
            if ($user->token) {
                $token = $user->token;
            } else {
                $token = md5(time() . json_encode($user));
                $user->token = $token;
                $user->save();
            }
            cookie('token', $token);
            $description = '登录操作，会员【' . $user->code . '】';
            Logs::adds($description, $this->admin['id'], $this->admin['admin_name']);
            return json(['code' => 1, 'msg' => '登录成功，正在跳转']);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function recharge()
    {
        $param = $this->request->param();

        if ($this->request->isAjax()) {
            switch ($param['type']) {
                case "get":
                    $user = $this->model::whereLike('code|mobile|nickname', '%' . $param['val'] . '%')
                        ->field('id,code,mobile,nickname')->select();
//                    $item = [];
//                    foreach ($user as $v) {
//                        $item[] = [
//                            'value'    => $v->id,
//                            'name'     => $v->code . '(' . $v->nickname . ')',
//                            'selected' => false,
//                            'disabled' => false,
//                        ];
//                    }
                    return json(['code' => 0, 'data' => $user]);
                case "account":
                    $assets = Assets::where('uid', $param['id'])->value($param['val']);
                    if ($assets) {
                        return json(['code' => 1, 'msg' => '', 'result' => $assets]);
                    } else {
                        return json(['code' => -1, 'msg' => '加载失败']);
                    }

                case "save":

                    try {

                        $this->validate($param, 'Recharge');

                    } catch (ValidateException $e) {
                        return json(['code' => -1, 'msg' => $e->getError()]);
                    }

                    return $this->model::recharge($param, $this->admin);

                default:
                    return json(['code' => -1, 'msg' => '加载失败']);

            }
        }
        View::assign('assets', Assets::getFields(3));
        return View::fetch();
    }

    
    //检查授权
    public function prorule($id = '')
    {
        $param = $this->request->param();
        //print($id);die;
        $info = $this->model::where(array('id' => $id))->find();
        if (isset($param['keyword'])) {
            $map['title'] = $param['keyword'];
            $keyword = $param['keyword'];
        } else {
            $keyword = '';
        }
        $map['is_del'] = 0;
        $userlist = Pro::where($map)->order('sort', 'asc')->paginate(['list_rows' => 20, 'query' => $this->request->param()]);
        foreach ($userlist as $k => $v) {
            $rule = $this->ruleModel::where(array('pro_id' => $v['id'], 'uid' => $id, 'is_del' => 0))->count();
            $v['rule'] = $rule > 0 ? 1 : 0;
            $userlist[$k] = $v;
        }

        View::assign('info', $info);
        View::assign('keyword', $keyword);
        View::assign('userlist', $userlist);
        return View::fetch();
    }


    //添加检查权限

    public function proRuleAdd(): Json
    {
        $param = $this->request->post();
        try {
            return json($this->ruleModel::proRuleAdd($param));
        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        }
    }

    public function export()
    {
        $name = '会员列表' . date('Y-m-d H:i:s');
        $s = $this->setMap($this->request->get('name'));
        $s['with'] = $this->hasOne;

        $title = TableFront::getInstance()->getFieldTable($this->request->get('name'));
        if (empty($title)) {
            return json(['code' => -1, 'msg' => '导出失败，请清除缓存后重试！']);
        }
        $s['filed'] = 'id,code,nickname,mobile,level_id,parent_code,create_time,is_lock';
        // if (isset($s['param']['is_active']) && $s['param']['is_active'] == 2) {
        //     $s['filed'] .= ',active_time';
        //     if (isset($s['param']['is_service']) && $s['param']['is_service'] == 1) {
        //         $name = '服务中心列表' . date('Y-m-d H:i:s');
        //     } else {
        //         $name = '正式会员列表' . date('Y-m-d H:i:s');
        //     }
        // }

       // $assets = Assets::getFields(3);
        $list = $this->model::getSelect($s);

        // foreach ($list['data'] as &$v) {
        //     foreach ($assets as $key => $item) {
        //         $v->$key = $v->assets->$key;
        //     }
        //     $v->level_id = $v->level ? $v->level->title : '暂无';
        //     $v->is_lock = $v->is_lock ? '是' : '否';
        //     unset($v->level);
        //     unset($v->assets);
        // }


        return json(['code' => 1, 'result' => ['data' => $list['data']->toArray(), 'title' => $title, 'name' => $name]]);
    }


}
